#-*- coding: UTF-8 -*-
import socket,sys,time,getopt,re
from threading import Thread,activeCount,Lock
mutex = Lock()

class Loop(Thread):
    def __init__(self,ip,port,que):
        Thread.__init__(self)
        self.ip     = ip
        self.port   = port
        self.que    = que

    def run(self):
        global mutex
        try:
            client = socket.socket()
            client.settimeout(3)
            indicator = client.connect_ex((self.ip,self.port))
            if mutex.acquire(1):
                if indicator == 0:
                    que.append(self.ip+'\t'+str(self.port))
                else:
                    #print self.ip,'\t',str(self.port),u'不可达'
                    pass
                mutex.release()
        except:
            if mutex.acquire(1):
                #print self.ip,'\t',str(self.port),u'不可达'
                mutex.release()
        finally:
            client.close()

class Main(Thread):
    def __init__(self,ip,que):
        Thread.__init__(self)
        self.ip  = ip
        self.que = que

    def run(self):
        i = 1
        while i < 65536:
            if i%100==1:
              sys.stdout.write(str(i)+u'端口检查中\r')
            if activeCount() <= 500:
              Loop(ip=self.ip,port=i,que=self.que).start()
              i = i + 1

def ipFormatChk(ip_str):
   pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
   if re.match(pattern, ip_str):
      return True
   else:
      return False
      
def  usage():
  print "-h help"
  print u"-i IP地址或域名"
  
if __name__ == '__main__':
    try:
      opts, args = getopt.getopt(sys.argv[1:], "hi:")
    except:
      sys.exit()
    
    ip=''
    for op, value in opts:
        if op == "-h":
           usage()
           sys.exit()
        elif op== "-i":
           ip=value
        else:
           usage()
           sys.exit()
    
    if ip=='':
      usage()
      sys.exit()
    
    if not ipFormatChk(ip):
      try:
        ipresults = socket.getaddrinfo(ip, None, 0, socket.SOCK_STREAM)
        print ipresults
        ipaddrs = [x[4][0] for x in ipresults]
        print ip+u'有'+str(len(ipaddrs))+u'个ip地址'
        if len(ipaddrs)>0:
          ip=ipaddrs[0]
        else:
          print u'没有查找到对应的ip地址'
          sys.exit()
      except Exception,e:
        print e
        sys.exit()

    que = []
    main = Main(ip = ip,que = que)
    main.start()

    while True:
        if activeCount() <= 1 and main.isAlive() == False:
            break

    for i in range(0,len(que)):
        print que[i]